from django.http import HttpResponse
from django.shortcuts import render
import hashlib
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from .models import User

# Create your views here.
import json
import time
import jwt
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import hashlib
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .models import User
from tools.login_dec import login_check


class UserView(View):
    def post(self, request):
        # 1 接收从前端提交的json串
        json_str = request.body
        # 2 将json串反序列化为python对象
        py_obj = json.loads(json_str)
        # 3 从对象中取出每一个数据
        username = py_obj['username']
        password_1 = py_obj['password_1']
        password_2 = py_obj['password_2']
        nickname = py_obj["nickname"]
        if not username:
            result = {'code': 10100, 'error': '用户名不能为空！'}
            return JsonResponse(result)
        if password_1 != password_2:
            result = {'code': 10101, 'error': '两次密码不一致！'}
            return JsonResponse(result)
        if not nickname:
            result = {'code': 10105, 'error': '请输入昵称！'}
            return JsonResponse(result)
        try:
            user = User.objects.create_user(username=username,
                                            password=password_1,
                                            nickname=nickname)
        except:
            result = {'code': 10102, 'error': '用户名不能重复！'}
            return JsonResponse(result)
        # 使用token技术存储登录信息
        token = make_token(user.id)
        token = token.decode()
        return JsonResponse({
            'code': 200,
            'token': token,
            'data': {
                'username': username,
                'userid': user.id,
                'avatar': str(user.avatar),
                'nickname': user.nickname,
            }
        })

    @method_decorator(login_check)
    def put(self, request, username):
        # 2.获取前端提交的数据,request.body
        json_str = request.body
        # 3.将json串反序列化为python对象
        py_obj = json.loads(json_str)
        # 4.获取用户对象,request.myuser
        user = request.myuser
        # 5.修改对象中的三个属性
        user.nickname = py_obj["nickname"]
        user.sign = py_obj["sign"]
        user.info = py_obj["info"]
        # 6.保存
        user.save()
        # 7.返回   响应
        return JsonResponse({"code": 200, "username": user.username})


def make_token(userid, expire=3600 * 24):
    # 1 准备payload
    now = time.time()
    payload = {
        'userid': userid,
        'exp': expire + now
    }
    # 2 准备key
    key = settings.JWT_TOKEN_KEY
    # 3 生成token并返回 返回类型：bytes
    return jwt.encode(payload, key)


@login_check
def user_avatar(request, username):
    # 头像上传[修改登录用户的头像]
    if request.method != "POST":
        return HttpResponse("头像上传失败")
    # 1.从请求对象中获取要修改的用户
    user = request.myuser
    # 2.使用上传的图片文件,修改头像
    user.avatar = request.FILES["avatar"]
    # 3.保存新的头像
    user.save()
    return JsonResponse({"code": 200})
